/* 
 * This file part of cget - A libcurl based downloading tool.
 * http://lianwei3.googlepages.com/home2
 * Copyright (C) 2006 Wei Lian <lianwei3@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "header.h"

extern pthread_mutex_t lock;

size_t my_write_func(void *ptr, size_t size, size_t nmemb, void *stream)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;
    pthread_mutex_lock(&lock);
    fseeko(info->fp, info->seek, SEEK_SET);	//share
    size_t nsize = size * nmemb;
    size_t dis = 0;
    while (nsize) {
	size_t re = fwrite((char *) ptr + dis, 1, nsize, info->fp);	//share
	info->seek += re;
	nsize -= re;
	dis += re;
    }
    pthread_mutex_unlock(&lock);
    return size * nmemb;
}

int my_progress_func(void *stream, double t, double d, double ut,
		     double un)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;
    int row, col;
    getmaxyx(stdscr, row, col);
    char str[col];
    snprintf(str, sizeof(str),
	     "(%d) download=%10.f, totoal=%10.f, (%3.f %%)%s", info->num,
	     d, t, d * 100.0 / t, info->url);
    mvprintw(info->num + 1, 1, str);
    refresh();
    return 0;
}

void *pull_one_url(void *stream)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;

    CURL *curl = info->curl;
    curl_easy_reset(curl);
    curl_easy_setopt(curl, CURLOPT_URL, info->url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, info);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func);
    curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, info);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
  NEXT:
    assert(info->seek >= 0);
    assert(info->seek <= info->end);
    char range[64];
    sprintf(range, "%ld-%ld", info->seek, info->end);
    curl_easy_setopt(curl, CURLOPT_RANGE, range);
    curl_easy_perform(curl);
    ////////
    std::vector < BlockInfo > *vec_info = info->vecptr;
    off_t max = 1024;
    int slowest_id = -1;
    off_t remain;
    ///find the slowest downloading thread
    pthread_mutex_lock(&lock);
    for (uint i = 0; i < vec_info->size(); i++) {
	remain = vec_info->at(i).end - vec_info->at(i).seek;	//share
	if (remain > max) {
	    max = remain;
	    slowest_id = i;
	}
    }
    assert(slowest_id != info->num);
    ///reallocate downloading jobs between the slowest and the finished threads
    if (slowest_id != -1) {
	///cancel the slowest thread
	pthread_cancel(*(vec_info->at(slowest_id).thread));	//share
	int error = pthread_join(*(vec_info->at(slowest_id).thread), NULL);	//share
	assert(error == 0);
	curl_easy_cleanup(vec_info->at(slowest_id).curl);	//share
	///reallocate ranges
	off_t mid = vec_info->at(slowest_id).end - max / 2;	//share
	info->seek = mid + 1;
	info->end = vec_info->at(slowest_id).end;	//share
	assert(vec_info->at(slowest_id).seek == vec_info->at(slowest_id).end - max);	//share
	vec_info->at(slowest_id).end = mid;	//share
	///create new job for the slowest thread
	vec_info->at(slowest_id).curl = curl_easy_init();	//share
	error = pthread_create(vec_info->at(slowest_id).thread, NULL, pull_one_url, &(vec_info->at(slowest_id)));	//share
	assert(error == 0);
	pthread_mutex_unlock(&lock);

	goto NEXT;
    }
    pthread_mutex_unlock(&lock);

    ///cleanup
    curl_easy_cleanup(curl);
    info->finished = TRUE;	//share
    return NULL;
}

//-----------------------------------------------------------------------
size_t my_header_func(void *ptr, size_t size, size_t nmemb, void *stream)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;
    char *str;
    if ((str = strstr((char *) ptr, "Content-Length:")))
	info->length = strtoll(str + strlen("Content-Length:"), NULL, 0);
    return size * nmemb;
}

void *consistency_check(void *stream)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;

    CURL *curl = info->curl;
    curl_easy_setopt(curl, CURLOPT_URL, info->url);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, my_header_func);
    curl_easy_setopt(curl, CURLOPT_WRITEHEADER, info);
    curl_easy_setopt(curl, CURLOPT_NOBODY, TRUE);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    curl_easy_perform(curl);

    return NULL;
}
